<template>
  <div class="order-container">
    <el-tabs v-model="activeTab" class="order-tabs">
      <el-tab-pane label="全部订单" name="all"></el-tab-pane>
      <el-tab-pane label="待付款" name="unpaid"></el-tab-pane>
      <el-tab-pane label="待配送" name="undelivered"></el-tab-pane>
      <el-tab-pane label="已配送" name="delivered"></el-tab-pane>
      <el-tab-pane label="已完成" name="completed"></el-tab-pane>
      <el-tab-pane label="已取消" name="canceled"></el-tab-pane>
    </el-tabs>

    <div class="order-list" v-loading="loading" element-loading-text="加载中...">
      <el-empty v-if="!loading && filteredOrders.length === 0" description="暂无订单"></el-empty>
      <div class="order-grid">
        <el-card v-for="order in filteredOrders" :key="order.id" class="order-card">
          <div class="order-header">
            <div class="order-info">
              <div class="order-number">订单号：{{ order.number }}</div>
              <div class="order-time">{{ order.orderTime }}</div>
            </div>
            <el-tag :type="getOrderStatusType(order.status)" size="small">
              {{ getOrderStatusText(order.status) }}
            </el-tag>
          </div>
          <div class="order-content">
            <div v-if="order.items && order.items.length > 0" class="order-dishes">
              <div v-for="(item, index) in order.items.slice(0, 2)" :key="index" class="dish-item">
                <span class="dish-name">{{ item.dishName || item.name }}</span>
                <span class="dish-price">¥{{ item.price }}</span>
                <span class="dish-quantity">x{{ item.number || item.quantity }}</span>
              </div>
              <div v-if="order.items.length > 2" class="more-dishes">
                等{{ order.items.length }}件商品
              </div>
            </div>
            <div v-else class="no-items">
              暂无详情
            </div>
          </div>
          <div class="order-footer">
            <div class="order-total">
              <span>合计：</span>
              <span class="total-price">¥{{ order.amount }}</span>
            </div>
            <div class="order-actions">
              <el-button
                v-if="order.status === 1"
                type="primary"
                size="small"
                @click="payOrder(order)"
              >
                去支付
              </el-button>
              <el-button
                v-if="order.status === 3"
                type="success"
                size="small"
                @click="confirmOrder(order)"
              >
                确认收货
              </el-button>
              <el-button
                v-if="order.status === 4"
                type="primary"
                size="small"
                @click="reviewOrder(order)"
              >
                评价
              </el-button>
              <el-button
                size="small"
                @click="viewOrderDetail(order)"
              >
                详情
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { orderApi } from '../../api/index'

const router = useRouter()
const activeTab = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

// 订单数据
const orders = ref<any[]>([])

// 根据标签筛选订单
const filteredOrders = computed(() => {
  let result;
  if (activeTab.value === 'all') {
    result = orders.value
  } else {
    const statusMap: Record<string, number> = {
      'unpaid': 1,
      'undelivered': 2,
      'delivered': 3,
      'completed': 4,
      'canceled': 5
    }
    result = orders.value.filter(order => order.status === statusMap[activeTab.value])
  }

  // 更新总数为当前筛选后的记录数
  total.value = result.length
  console.log('标签切换后的记录数:', result.length)

  return result
})

// 获取订单状态文本
const getOrderStatusText = (status: number) => {
  switch (status) {
    case 1: return '待付款'
    case 2: return '待配送'
    case 3: return '已配送'
    case 4: return '已完成'
    case 5: return '已取消'
    default: return '未知状态'
  }
}

// 获取订单状态类型
const getOrderStatusType = (status: number) => {
  switch (status) {
    case 1: return 'warning' // 将"待付款"状态改为黄色(warning)
    case 2: return 'primary' // 将"待配送"状态改为蓝色(primary)
    case 3: return 'success'
    case 4: return 'success' // 将"已完成"状态改为绿色(success)
    case 5: return 'danger'
    default: return 'info'
  }
}

// 获取订单商品总数量
const getTotalQuantity = (order: any) => {
  return order.items.reduce((total: number, item: any) => total + item.quantity, 0)
}

// 加载订单数据
const loadOrders = async () => {
  loading.value = true
  try {
    console.log('正在加载用户订单，页码:', currentPage.value, '每页数量:', pageSize.value)
    const res = await orderApi.getUserOrders(currentPage.value, pageSize.value)
    console.log('后端返回的订单数据:', res.data)

    orders.value = res.data.records || []
    total.value = res.data.total || 0

    console.log('订单记录数:', orders.value.length, '总记录数:', total.value)

    // 总数会在 filteredOrders computed 属性中自动更新

    // 加载订单详情
    for (const order of orders.value) {
      try {
        const detailRes = await orderApi.getOrderDetail(order.id)
        // 检查是否存在orderDetails字段
        if (detailRes.data && detailRes.data.orderDetails) {
          // 将orderDetails映射为items，以保持前端代码一致性
          order.items = detailRes.data.orderDetails.map((detail: any) => ({
            dishId: detail.dishId,
            dishName: detail.dishName,
            price: detail.price,
            number: detail.number,
            amount: detail.amount,
            image: detail.image
          }))
        } else {
          // 如果没有orderDetails，设置一个空数组
          order.items = []
        }
      } catch (error) {
        console.error(`获取订单${order.id}详情失败:`, error)
        order.items = []
      }
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadOrders()
}

// 当前页变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadOrders()
}

// 支付订单
const payOrder = async (order: any) => {
  ElMessageBox.confirm(`确定要支付订单 ${order.number} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 显示加载中
      const loading = ElLoading.service({
        lock: true,
        text: '支付处理中...',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      // 调用支付接口
      await orderApi.payOrder(order.id)

      // 关闭加载
      loading.close()

      // 显示成功消息
      ElMessage.success('支付成功')

      // 重新加载订单数据
      loadOrders()
    } catch (error: any) {
      ElMessage.error(error.message || '支付失败，请稍后再试')
    }
  }).catch(() => {
    // 用户取消支付
  })
}

// 确认收货
const confirmOrder = async (order: any) => {
  ElMessageBox.confirm(`确定已收到订单 ${order.number} 的商品吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await orderApi.completeOrder(order.id)
      ElMessage.success('确认收货成功')
      // 重新加载订单数据
      loadOrders()
    } catch (error: any) {
      ElMessage.error(error.message || '确认收货失败')
    }
  }).catch(() => {})
}

// 评价订单
const reviewOrder = (order: any) => {
  router.push({
    path: '/user/feedback',
    query: { orderId: order.id }
  })
}

// 取消订单
const cancelOrder = async (order: any) => {
  ElMessageBox.confirm(`确定要取消订单 ${order.number} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await orderApi.cancelOrder(order.id)
      ElMessage.success('订单已取消')
      // 重新加载订单数据
      loadOrders()
    } catch (error: any) {
      ElMessage.error(error.message || '取消订单失败')
    }
  }).catch(() => {})
}

// 查看订单详情
const viewOrderDetail = (order: any) => {
  // 构建菜品列表HTML
  let dishesHtml = '';
  if (order.items && order.items.length > 0) {
    dishesHtml = '<div style="margin-top: 10px; margin-bottom: 10px;"><strong>订单菜品：</strong></div><ul style="padding-left: 20px; margin-top: 5px;">';
    order.items.forEach((item: any) => {
      dishesHtml += `<li>${item.dishName || item.name} - ¥${item.price} x ${item.number || item.quantity}</li>`;
    });
    dishesHtml += '</ul>';
  } else {
    dishesHtml = '<div style="margin-top: 10px; margin-bottom: 10px;"><strong>订单菜品：</strong> 暂无菜品信息</div>';
  }

  ElMessageBox.alert(
    `订单号：${order.number}<br>
    下单时间：${order.orderTime}<br>
    订单状态：${getOrderStatusText(order.status)}<br>
    ${dishesHtml}
    订单金额：<span style="color: #f56c6c; font-weight: bold;">¥${order.amount}</span>`,
    '订单详情',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确定'
    }
  )
}

// 组件挂载时加载订单数据
onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
.order-container {
  padding: 20px;
}

.order-tabs {
  margin-bottom: 20px;
}

/* 修复标签样式 */
.order-tabs :deep(.el-tabs__nav-wrap::after) {
  height: 1px !important; /* 减小底部线的高度 */
}

.order-tabs :deep(.el-tabs__header) {
  margin-bottom: 15px; /* 调整标签与内容的间距 */
}

.order-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.order-card {
  width: 100%;
  transition: all 0.3s;
}

.order-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-3px);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.order-info {
  display: flex;
  flex-direction: column;
}

.order-number {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.order-time {
  font-size: 12px;
  color: #999;
}

.order-content {
  min-height: 60px;
  margin-bottom: 10px;
}

.order-dishes {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.dish-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 13px;
}

.dish-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-weight: 500;
}

.dish-price {
  margin: 0 10px;
  color: #555;
}

.dish-quantity {
  color: #999;
}

.more-dishes {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.order-footer {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

.order-total {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.total-price {
  color: #f56c6c;
  font-size: 16px;
  font-weight: bold;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.no-items {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
  color: #999;
  font-size: 13px;
}

@media screen and (max-width: 768px) {
  .order-grid {
    grid-template-columns: 1fr;
  }
}
</style>
